<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               v-model:page="page"
               v-model:search="search"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @sort-change="sortChange"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               :row-class-name="rowClassName"
               :cell-class-name="rowClassName"
               @on-load="onLoad">
      <template  #menu-left>
        <el-button type="primary" icon="el-icon-plus" v-if="permission.prod_main_add" @click="handleAdd">新 增
        </el-button>
        <!--<el-button type="danger"-->
                   <!--icon="el-icon-delete"-->
                   <!--v-if="permission.prod_main_delete"-->
                   <!--@click="handleDelete">删 除-->
        <!--</el-button>-->
      </template>
        <template #tabDate-search="{ disabled, size }">
            <!--<div style="display: flex;flex-direction: start;">-->
                <!--<el-select v-model="search.tabDateRule" placeholder="比较" filterable clearable>-->
                    <!--<el-option label="" value=""></el-option>-->
                    <!--<el-option value=">" label="大于">大于 </el-option>-->
                    <!--<el-option value=">=" label="大于等于">大于等于 </el-option>-->
                    <!--<el-option value="=" label="等于">等于 </el-option>-->
                    <!--<el-option value="!=" label="不等于">不等于 </el-option>-->
                    <!--<el-option value="<=" label="小于等于">小于等于 </el-option>-->
                    <!--<el-option value="<" label="小于">小于 </el-option>-->
                <!--</el-select>-->
                <!--<el-date-picker-->
                        <!--size="default"-->
                        <!--v-model="search.tabDateSearch"-->
                        <!--type="date"-->
                        <!--:format="dateFormat"-->
                        <!--:value-format="dateFormat"-->
                        <!--:unlink-panels="true"-->
                        <!--clearable-->
                        <!--placeholder="生效日期"-->
                        <!--:picker-options="pickerOptions"-->
                <!--&gt;-->
                <!--</el-date-picker>-->
            <!--</div>-->
            <el-date-picker
                    size="default"
                    style="width:94%"
                    v-model="this.tabDateRange"
                    type="daterange"
                    :format="dateFormat"
                    :value-format="dateFormat"
                    unlink-panels
                    start-placeholder="Start Date"
                    end-placeholder="End Date"
                    clearable
                    placeholder="排单日期"
                    @change="handleDatePickerChange"
                    :picker-options="pickerOptions"
            >
            </el-date-picker>
        </template>
        <!--<template #createDate-search="{ disabled, size }">-->
            <!--<div style="display: flex;flex-direction: start;">-->
                <!--<el-select v-model="search.createTimeRule" placeholder="比较" filterable clearable>-->
                    <!--<el-option label="" value=""></el-option>-->
                    <!--<el-option value=">" label="大于">大于 </el-option>-->
                    <!--<el-option value=">=" label="大于等于">大于等于 </el-option>-->
                    <!--<el-option value="=" label="等于">等于 </el-option>-->
                    <!--<el-option value="!=" label="不等于">不等于 </el-option>-->
                    <!--<el-option value="<=" label="小于等于">小于等于 </el-option>-->
                    <!--<el-option value="<" label="小于">小于 </el-option>-->
                <!--</el-select>-->
                <!--<el-date-picker-->
                        <!--size="default"-->
                        <!--v-model="search.createTimeSearch"-->
                        <!--type="date"-->
                        <!--:format="dateFormat"-->
                        <!--:value-format="dateFormat"-->
                        <!--:unlink-panels="true"-->
                        <!--clearable-->
                        <!--placeholder="操作日期"-->
                        <!--:picker-options="pickerOptions"-->
                <!--&gt;-->
                <!--</el-date-picker>-->
            <!--</div>-->
        <!--</template>-->
        <template #menu="{ row, size, type }">
            <el-tooltip content="查看" placement="top">
                <el-button
                        icon="el-icon-view"
                        link
                        :size="size"
                        :type="type"
                        @click="() => handleView(row)"
                        v-if="permission.prod_main_view"
                >
                </el-button>
            </el-tooltip>
            <el-tooltip content="编辑" placement="top">
                <el-button
                        icon="Edit"
                        link
                        :size="size"
                        :type="type"
                        @click="() => handleEdit(row)"
                        v-if="permission.prod_main_edit && row.prodStatus=='未审核'"
                >
                </el-button>
            </el-tooltip>
            <el-tooltip content="审核" placement="top" v-if="row.prodStatus =='未审核'">
                <el-button
                        icon="EditPen"
                        link
                        :size="size"
                        :type="type"
                        @click="() => handleAudit(row)"
                        v-if="permission.prod_main_audit"
                >
                </el-button>
            </el-tooltip>
            <el-tooltip content="反审核" placement="top" v-if="row.prodStatus =='已审核'">
                <el-button
                        icon="NoSmoking"
                        link
                        :size="size"
                        :type="type"
                        @click="() => rollbackAudit(row)"
                        v-if="permission.prod_main_audit"
                >
                </el-button>
            </el-tooltip>
            <el-tooltip content="生产报表" placement="top">
                <el-button
                        icon="Reading"
                        link
                        :size="size"
                        :type="type"
                        @click="() => showChoice(row)"
                >
                </el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top" v-if="row.prodStatus =='未审核'">
                <el-button
                        icon="el-icon-delete"
                        link
                        :size="size"
                        :type="type"
                        @click="() => rowDel(row)"
                        v-if="permission.prod_main_delete"
                >
                </el-button>
            </el-tooltip>
        </template>
    </avue-crud>
      <prod-form ref="prodForm" @success="refreshChange"></prod-form>
      <el-dialog title="生产单预览" append-to-body v-model="box" width="30%" @close="previewClose">
<!--          <el-form-item label="语言">-->
<!--              <el-radio-group v-model="isEnglish" class="list">-->

<!--                  <el-radio label="1" >中文</el-radio>-->
<!--                  <el-radio label="2" >英文</el-radio>-->
<!--              </el-radio-group>-->
<!--          </el-form-item>-->
          <el-form-item label="BOM表">
              <el-radio-group v-model="hiddenBom" class="list">

                  <el-radio label="1" >显示BOM表</el-radio>
                  <el-radio label="2" >不显示BOM表</el-radio>
              </el-radio-group>
          </el-form-item>
          <template #footer>
        <span class="dialog-footer">
          <el-button @click="this.box = false">取 消</el-button>
          <el-button type="primary" @click="prodReport">预 览</el-button>
        </span>
          </template>
      </el-dialog>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove,prodReport,changeStatus,checkProdByStock} from "@/api/anwise/prod/prod_main";
  import {mapGetters} from "vuex";
  import prodForm from './components/prod_form.vue';
  import {userCompany} from "@/api/anwise/common";

  export default {
      components: {
          prodForm,
      },
    data() {
      return {
        form: {},
        query: {},
          tabDateRange:[],
        loading: true,
          data:[],
        page: {
          pageSize: 20,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
            height:'auto',
            calcHeight: 30,
            tip: false,
            searchShow: false,
            searchMenuSpan: 6,
            border: true,
            index: true,
            selection: true,
            reserveSelection:true,
            labelWidth: 150,
            indexWidth:100,
            menuWidth: 210,
            addBtn: false,
            editBtn: false,
            viewBtn: false,
            delBtn: false,
            stripe: true,
            searchIndex: 3,
            searchIcon: false,
            searchLabelWidth:100,
            searchEnter:true,
          column: [
              {
                  label: "排单日期",
                  prop: "tabDate",
                  type: "input",
                  search: true,
                  width:150,
                  overHidden: true,
                  sortable: true,
              },
            {
              label: "生产单号",
              prop: "tabNo",
              type: "input",
              search: true,
                width:150,
                overHidden: true,
                sortable: true,
            },
              {
                  label: "版本",
                  prop: "version",
                  type: "input",
                  width:100,
                  overHidden: true,
                  sortable: true,
              },
            {
              label: "加工商账号",
              prop: "supplierNo",
                type: "number",
                precision:0,
                min:1,
                controls:false,
              search: true,
                width:130,
                overHidden: true,
                sortable: true,
            },
            {
              label: "加工商名称",
              prop: "supplierName",
              type: "input",
              search: true,
                width:130,
                overHidden: true,
                sortable: true,
            },
            {
              label: "备注",
              prop: "remark",
              type: "input",
                width:200,
                overHidden: true,
                sortable: true,
            },
              {
                  label: "审批状态",
                  prop: "prodStatus",
                  type: "select",
                  dicUrl: "/blade-system/dict-biz/dictionary?code=approve_status",
                  filterable: true,
                  overHidden: true,
                  sortable: true,
                  search:true,
                  width:150,
                  props: {
                      label: 'dictValue',
                      value: 'dictKey',
                  },
                  dataType: 'string',
                  rules: [{
                      required: true,
                      message: "请输入审批状态",
                      trigger: "blur"
                  }],
              },
            {
              label: "审批人",
              prop: "approver",
              type: "input",
                width:130,
                overHidden: true,
                sortable: true,
            },
            {
              label: "审批时间",
              prop: "approverDate",
              type: "input",
                width:150,
                overHidden: true,
                sortable: true,
            },
              {
                  label: "操作人员",
                  prop: "createUserName",
                  filterable: true,
                  type: "input",
                  // hide: true,
                  overHidden: true,
                  sortable: true,
                  width:120,
              },
              {
                  label: "操作时间",
                  prop: "createTime",
                  type: "input",
                  // hide: true,
                  overHidden: true,
                  sortable: true,
                  width:150,
              },
              {
                  label: "操作时间",
                  prop: "createDate",
                  type: "input",
                  hide: true,
                  sortable: true,
                  width:150,
              },
          ]
        },
        data: [],
        selectId:'',
        box:false,
        isEnglish:"1",
          hiddenBom:'1',
        search: {},
        dateFormat:"YYYY-MM-DD"
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.validData(this.permission.prod_main_add, false),
          viewBtn: this.validData(this.permission.prod_main_view, false),
          delBtn: this.validData(this.permission.prod_main_delete, false),
          editBtn: this.validData(this.permission.prod_main_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
        rowClassName({row, rowindex}) {
            if (row.prodStatus ==='未审核') {
                return 'row-yellow';
            }
        },
        rollbackAudit(row) {
            this.loading = true;
            if (!this.permission.prod_super) {
                checkProdByStock(row).then(res => {
                    this.loading = false;
                    if (res.data.success) {
                        changeStatus(row.id, 2).then(res => {
                            if (res.data.success) {
                                this.onLoad(this.page);
                                this.$message({
                                    type: "success",
                                    message: res.msg || "反审核成功!"
                                });
                            }
                        })
                    }
                }).catch(() => {
                    this.loading = false;
                });
            } else {
                changeStatus(row.id, 2).then(res => {
                    if (res.data.success) {
                        this.onLoad(this.page);
                        this.$message({
                            type: "success",
                            message: res.msg || "反审核成功!"
                        });
                    }
                })
            }
        },
        handleAudit(row) {
            this.loading = true;
            changeStatus(row.id, 1).then(res => {
                this.loading = false;
                if (res.data.success) {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: res.msg || "审核成功!"
                    });
                }
            }).catch(() => {
                this.loading = false;
            });
        },
        previewClose() {
            this.isEnglish='1';
            this.selectId='';
        },
        showChoice(row){
            this.selectId= row.id;
            this.box = true;

            // prodReport(this.selectId, this.isEnglish,this.hiddenBom).then(res => {
            //     if(res.data.success) {
            //         const file = res.data.data;
            //         const originUrl = (file.url.replace(file.domain, `${this.res}/`));
            //         const url = file.url;
            //         // this.$refs.preview.open({
            //         //     url: url || "",
            //         //     originUrl: originUrl || ""
            //         // });
            //         console.log(url)
            //         window.open(`/plugins/pdfjs/web/viewer.html?file=`+url);
            //     }
            // })

        },
        prodReport(id) {
            prodReport(this.selectId, this.isEnglish,this.hiddenBom).then(res => {
                if(res.data.success) {
                    const file = res.data.data;
                    // const originUrl = (file.url.replace(file.domain, `${this.res}/`));
                    const url = file.url;
                    // this.$refs.preview.open({
                    //     url: url || "",
                    //     originUrl: originUrl || ""
                    // });
                    console.log(url)
                    window.open(`/plugins/pdfjs/web/viewer.html?file=`+url);
                }
            })
        },
        handleView(row) {
            let title="查看生产单信息";
            let type='view';
            const id = row.id;
            this.$refs.prodForm.show({
                id,
                title,
                type
            })
        },
        handleEdit(row) {
            let title="生产单信息";
            let type='edit';
            const id = row.id;
            this.$refs.prodForm.show({
                id,
                title,
                type
            })
        },
        handleAdd() {
            userCompany().then(res => {
                if (res.data.success) {
                    this.dept = res.data.data;
                    if (!this.dept) {
                        this.$message({
                            type: "error",
                            message: "用户无组织机构信息，请联系安伟工作人员！"
                        });
                    } else {
                        let title="生产单信息";
                        let type='edit';
                        this.$refs.prodForm.show({
                            title,
                            type
                        })
                    }
                }
            })
        },
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
        sortChange(val) {
            console.log(val)
            this.sort = {
                prop: val.prop,
                order: val.order
            };
            let order = "";
            if (this.sort.prop && this.sort.order) {
                if (this.sort.order === "descending") {
                    order = `${this.sort.prop} desc`
                } else {
                    order = `${this.sort.prop} asc`
                }
            }
            this.query.orderBy = order;
            this.onLoad(this.page);
        },
      searchReset() {
        this.query = {};
          this.tabDateRange = [];
          this.search.tabDateStart = '';
          this.search.tabDateEnd = '';
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          console.log("data",data);
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
        handleDatePickerChange(value) {
            console.log(value);
            if (value) {
                this.search.tabDateStart = value[0];
                this.search.tabDateEnd = value[1];
            } else {
                this.search.tabDateStart = '';
                this.search.tabDateEnd = '';
            }
        },
    }
  };
</script>

<style scoped>
    .row-yellow {
        background-color: rgb(255, 253, 230) !important;
        cursor: pointer;
    }
</style>
